class Solution:
    '''
    Input: [1, 5, 11, 5]
    Output: true
    Explanation: The array can be partitioned as [1, 5, 5] and [11].
    '''
    def canPartition(self, nums):
        """
        :type nums: List[int]
        :rtype: bool
        """
        n = len(nums)
        if n==0:
            return False
        sums = sum(nums)
        if sums % 2==1:
            return  False
        middle =  int(sums/2)

        # f = [[False] * (middle+1) for _ in range(n+1)]
        # f[0][0] = True
        #
        # for i in range(1,n+1):
        #     for j in range(middle+1):
        #         f[i][j] = f[i - 1][j]
        #         if j>=nums[i-1]:
        #             f[i][j] = f[i][j] or f[i-1][j-nums[i-1]]
        # print(f)
        # return f[-1][-1]




#         优化
        f = [False] * (middle+1)
        f[0] = True

        for i in range(1,n+1):
            for j in range(middle,-1,-1):
                if j>=nums[i-1]:
                    f[j] = f[j] or f[j-nums[i-1]]
        return f[-1]


s = Solution()
m = s.canPartition([1, 5, 11, 5])
print(m)